//
//  MTTicketVC.m
//  met
//
//  Created by 李晓俊 on 2019/5/11.
//  Copyright © 2019 李晓俊. All rights reserved.
//

#import "MTTicketVC.h"
//兑换记录
#import "MTRecordVC.h"
#import "MTTicketView.h"

#import "MTStepVC.h"
#import <UShareUI/UShareUI.h>
#import "MTYaoQingView.h"
#import "MTRechargeView.h"
@interface MTTicketVC ()<UMSocialShareMenuViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *bgView;
@property (weak, nonatomic) IBOutlet UILabel *chepiaoCount;
@property (weak, nonatomic) IBOutlet UIButton *rechargeBut;

@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) NSString *jumpUrl;

@property (nonatomic, strong) NSString *productId;

@end

@implementation MTTicketVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.rechargeBut.layer.borderWidth = 2;
    self.rechargeBut.layer.borderColor = KBlackColor.CGColor;
    
    [self customNavItem];
    self.tableView.backgroundColor = KBackColor;
    self.view.backgroundColor = KBackColor;

    UIView *foot = [UIView new];
    foot.backgroundColor = KBackColor;
    self.tableView.tableFooterView = foot;
    
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.contentSize = CGSizeMake(26+138*3, 266);
    self.scrollView.frame = CGRectMake(0, 0, kScreenWidth, 266);
    self.scrollView.showsHorizontalScrollIndicator = NO;
    [self.bgView addSubview:self.scrollView];
    
    MTTicketView *first = [[MTTicketView alloc] initWithFrame:CGRectMake(26, 0, 128, 229)];
    first.numberimage.image = [UIImage imageNamed:@"车票1"];
    first.buttonClick = ^(NSString *  s) {
        MTStepVC *vc = GetViewControllerInStoryboard(@"Mine", @"MTStepVC");
        [self.navigationController pushViewController:vc animated:YES];
    };
    [self.scrollView addSubview:first];
    
    MTTicketView *second = [[MTTicketView alloc] initWithFrame:CGRectMake(26 + 138 *1, 0, 128, 229)];
    second.numberimage.image = [UIImage imageNamed:@"车票2"];
    second.content.text =  @"每日签到";
    second.tishi.text =  @"可获得5车票";
    second.count.text =  @"+5";
    [second.goBut setTitle:@"去签到" forState:UIControlStateNormal];
    
    second.buttonClick = ^(NSString * s) {
        if ([[NSString stringWithFormat:@"%@",KUSER.isSign]isEqualToString:@"1"]) {
            //已签到
            [[UIApplication sharedApplication].keyWindow maketishiToast:@"今日已签到"];
        }else {
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            AccountService *acc = [AccountService getObject];
            acc.httpRequestResultBlock = ^(id data,int code){
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                if (code == 1) {
                    [[UIApplication sharedApplication].keyWindow maketicket2Toast:@"5"];
                    [self getUserInfo];
                }else {
                    [self.view maketishiToast:data];
                }
            };
            [acc userSign];
        }
    };
    
    [self.scrollView addSubview:second];
    
    MTTicketView *third = [[MTTicketView alloc] initWithFrame:CGRectMake(26 + 138 *2 , 0, 128, 229)];
    third.numberimage.image = [UIImage imageNamed:@"车票3"];
    third.content.text =  @"邀请一位好友";
    third.tishi.text =  @"可获得10车票";
    third.count.text =  @"+10";
    [third.goBut setTitle:@"去邀请" forState:UIControlStateNormal];
    third.buttonClick = ^(NSString *  s) {

        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        AccountService *acc = [AccountService getObject];
        acc.httpRequestResultBlock = ^(id data,int code){
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if (code == 1) {
                if ([[NSString stringWithFormat:@"%@",[data objectForKey:@"model"]]isEqualToString:@"1"]) {

                }else {
                    //邀请链接
                   NSString *url = [NSString stringWithFormat:@"%@",[data objectForKey:@"content"]];
                    self.jumpUrl = url;
                    [self shareClick];
                }
            }else {
                [self.view maketishiToast:data];
            }
        };
        [acc findOthers:@"10"];
    };
    [self.scrollView addSubview:third];
    
    
    [UMSocialUIManager setShareMenuViewDelegate:self];
    
    self.jumpUrl = @"";
}
- (UIView*)UMSocialParentView:(UIView*)defaultSuperView
{
    return [UIApplication sharedApplication].keyWindow;
}
#pragma mark - 定制导航条内容
- (void)customNavItem {
    self.navigationItem.title = @"车票";
    UIButton *rightBtn = [[UIButton alloc] init];
    [rightBtn setTitle:@"兑换记录" forState:UIControlStateNormal];
    [rightBtn setTitleColor:KBlackColor forState:UIControlStateNormal];
    rightBtn.titleLabel.font = SBFONT(18);
    [rightBtn addTarget:self action:@selector(rightAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [WRNavigationBar wr_setDefaultNavBarBarTintColor:KWhiteColor];
//    [WRNavigationBar wr_setDefaultNavBarShadowImageHidden:NO];
    [self getUserInfo];
}
//- (void)viewWillDisappear:(BOOL)animated {
//    [super viewWillDisappear:animated];
//    [WRNavigationBar wr_setDefaultNavBarShadowImageHidden:YES];
//}
- (void)getUserInfo{
    //    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            KUSER = data;
            NSUserDefaults *userInfo = [NSUserDefaults standardUserDefaults];
            NSDictionary *dic = [KUSER mj_keyValues];
            //             操作者将包含用户信息的数组arr持久化
            [userInfo setValue:dic forKey:@"userinfo"];
            //把值立即存进去,放置数据丢失
            [[NSUserDefaults standardUserDefaults]synchronize];
           
            self.chepiaoCount.text = [NSString stringWithFormat:@"%@",KUSER.ticket];
            
        }else {
            [self.view maketishiToast:data];
        }
    };
    [acc findUserInfo];
}
- (void)rightAction {
    MTRecordVC *vc = [[MTRecordVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

//充值点击了
- (IBAction)rechargeClick:(id)sender {
    MTRechargeView *rgView = [[MTRechargeView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    rgView.rechargeDone = ^(NSString * _Nonnull num) {
        self.productId = [NSString stringWithFormat:@"chepiao0%@",num];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        AccountService *acc = [AccountService getObject];
        acc.httpRequestResultBlock = ^(id data,int code){
            if (code == 1) {
                NSString *orderId = [data objectForKey:@"data"];
                [[CLStoreManager defaultManager] startPayWithProductId:self.productId success:^(id responseObject) {
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                    [self paySuccess:orderId num:num];
                } failed:^(id responseObject) {
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                }];
            }else {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                [self.view maketishiToast:data];
            }
        };
        [acc ordersFindPrepayId:num];
    };

    [[UIApplication sharedApplication].keyWindow addSubview:rgView];
}
- (void)paySuccess:(NSString *)orderId num:(NSString *)num{
    NSString *buyNum = @"0";
    if ([num isEqualToString:@"1"]) {
        buyNum = @"72";
    }else if ([num isEqualToString:@"2"]) {
        buyNum = @"108";
    }else if ([num isEqualToString:@"3"]) {
        buyNum = @"204";
    }else if ([num isEqualToString:@"4"]) {
        buyNum = @"708";
    }
    
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            [[UIApplication sharedApplication].keyWindow maketicket2Toast:buyNum];
            [self getUserInfo];
        }else {
            [self.view maketishiToast:data];
        }
    };
    [acc ordersPaySuccess:orderId];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [UIView new];
    return v;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01f;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [UIView new];
    return view;
}

- (void)shareClick {
    //显示分享面板
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        // 根据获取的platformType确定所选平台进行下一步操作
        [self shareImageAndTextToPlatformType:platformType];
    }];
}
- (void)shareImageAndTextToPlatformType:(UMSocialPlatformType)platformType
{
    //创建分享标识
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //设置文本
    messageObject.text = @"";
    
    MTYaoQingView *yao = [[MTYaoQingView alloc] initWithFrame:CGRectMake(0, 0, 375, 667)];
    yao.codeView.image = [self createCode];
    
    UIImage *img = [self makeImageWithView:yao withSize:CGSizeMake(375, 667)];
    
    //创建图片内容对象
    UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
    //如果有缩略图，则设置缩略图
    shareObject.thumbImage = [UIImage imageNamed:@"AppIcon"];
    [shareObject setShareImage:img];
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;

    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
    }];
}

- (UIImage *)createCode{
    //
    NSArray *filters = [CIFilter filterNamesInCategory:kCICategoryBuiltIn];
    NSLog(@"%@",filters);
    //二维码过滤器
    CIFilter *qrImageFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    //设置过滤器默认属性
    [qrImageFilter setDefaults];
    //将字符串转换成 NSdata (虽然二维码本质上是 字符串,但是这里需要转换,不转换就崩溃)
    // 字符串可以随意换成网址等
    NSString *url = self.jumpUrl;
    
    NSData *qrImageData = [url dataUsingEncoding:NSUTF8StringEncoding];
    //我们可以打印,看过滤器的 输入属性.这样我们才知道给谁赋值
    NSLog(@"%@",qrImageFilter.inputKeys);
    //设置过滤器的 输入值 ,KVC赋值
    [qrImageFilter setValue:qrImageData forKey:@"inputMessage"];
    //取出图片
    CIImage *qrImage = [qrImageFilter outputImage];
    //但是图片 发现有的小 (27,27),我们需要放大..我们进去CIImage 内部看属性
    qrImage = [qrImage imageByApplyingTransform:CGAffineTransformMakeScale(20, 20)];
    //转成 UI的 类型
    UIImage *qrUIImage = [UIImage imageWithCIImage:qrImage];
    //----------------给 二维码 中间增加一个 自定义图片----------------
    //开启绘图,获取图形上下文 (上下文的大小,就是二维码的大小)
    UIGraphicsBeginImageContext(qrUIImage.size);
    //把二维码图片画上去. (这里是以,图形上下文,左上角为 (0,0)点)
    [qrUIImage drawInRect:CGRectMake(0, 0, qrUIImage.size.width, qrUIImage.size.height)];
    //再把小图片画上去
    UIImage *sImage = [UIImage imageNamed:@"icon108"];
    CGFloat sImageW = 100;
    CGFloat sImageH= sImageW;
    CGFloat sImageX = (qrUIImage.size.width - sImageW) * 0.5;
    CGFloat sImgaeY = (qrUIImage.size.height - sImageH) * 0.5;
    [sImage drawInRect:CGRectMake(sImageX, sImgaeY, sImageW, sImageH)];
    //获取当前画得的这张图片
    UIImage *finalyImage = UIGraphicsGetImageFromCurrentImageContext();
    //关闭图形上下文
    UIGraphicsEndImageContext();
    //设置图片
    return  finalyImage;
}

- (UIImage *)makeImageWithView:(UIView *)view withSize:(CGSize)size
{
    
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了，关键就是第三个参数 [UIScreen mainScreen].scale。
    UIGraphicsBeginImageContextWithOptions(size, YES, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
    
}
@end
